package com.haidao.admin.component.web.controller;

import com.haidao.admin.component.params.LoginParam;
import com.haidao.admin.component.service.UserService;
import com.haidao.admin.component.entity.User;
import com.haidao.admin.core.result.Err;
import com.haidao.admin.core.result.Resp;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import jakarta.validation.Valid;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import java.util.Base64;

@Slf4j
@RestController
public class IndexController {

    @Resource
    private UserService userService;

    @Value("${sso.redirect}")
    private String redirect;

    /**
     * 手机号码、密码登录
     */
    @PostMapping("/login")
    public Resp<?> login(@RequestBody @Valid LoginParam param) throws Exception {
        User user = userService.login(param);
        if (user == null) {
            return Resp.fail(Err.AUTHED_LOGIN_ERROR);
        }
        String token = userService.genToken(user);
        return Resp.ok(token);
    }

    @RequestMapping("/auth")
    public ModelAndView callback(HttpServletRequest request) throws Exception {
        String subjectDN = request.getHeader("X509Certificate.subjectDN");
        System.out.println("sbuject"+subjectDN);
        if (StringUtils.isNotEmpty(subjectDN)) {
            byte[] codes = Base64.getDecoder().decode(subjectDN);
            String userInfo = new String(codes).split(",")[0];
            String user = userInfo.split("=")[1];
            System.out.println("user"+user+","+userInfo);
            return new ModelAndView(new RedirectView(redirect + "?code="+user));
        }
        return new ModelAndView(new RedirectView(redirect));
    }
}